package cn.com.dingtek.genius.manager.server.support.sam;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.SignerVerifier;

@Slf4j
@Data
@NoArgsConstructor
public class SamToken {
    private Long userId;
    private String account;
    private long createTime;

    public String encode(SignerVerifier signerVerifier) {
        return JwtHelper.encode(JSON.toJSONString(this), signerVerifier).getEncoded();
    }

    public static SamToken decodeAndVerify(String jwtToken, SignerVerifier signerVerifier) {
        try {
            Jwt jwt = JwtHelper.decodeAndVerify(jwtToken, signerVerifier);
            return JSON.parseObject(jwt.getClaims(), SamToken.class);
        } catch (Exception e) {
            log.error("decode and verify jwt content error,jwtToken:{}", jwtToken, e);
        }

        return null;
    }
}
